<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-row>
<!--						<a-col :span="24">-->
<!--							<a-form-item label="工厂" v-bind="validateInfos.factoryId">-->
<!--								<j-search-select v-model:value="formData.factoryId" dict="p_factory_manage,name,code"  allow-clear />-->
<!--							</a-form-item>-->
<!--						</a-col>-->
						<a-col :span="24">
							<a-form-item label="包材" v-bind="validateInfos.packagingId" >
                <a-input placeholder="请输入名称" v-model:value="formData.name" allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="库存" v-bind="validateInfos.stock">
								<a-input-number v-model:value="formData.stock" placeholder="请输入库存" :precision="2"  style="width: 100%" />
							</a-form-item>
						</a-col>
            <a-col :span="24">
              <a-form-item label="单位" v-bind="validateInfos.unit">
                <j-search-select v-model:value="formData.unit" dict="unit_code"  allow-clear />
              </a-form-item>
            </a-col>

            <a-col :span="48">
              <a-form-item label="关联产品" v-bind="validateInfos.goodsNos">
                <j-select-multiple v-model:value="formData.goodsNos" :options="dictOptions"  allow-clear />
                <j-input :disabled="true" v-model:value="formData.goodsNo" ></j-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import {ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, watch, unref} from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';

  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../PackagingDetails.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import {initDictOptions} from "@/utils/dict";
  import { useUserStore } from '/@/store/modules/user';
  import JInput from "@/components/Form/src/jeecg/components/JInput.vue";
  import JSelectMultiple from "@/components/Form/src/jeecg/components/JSelectMultiple.vue";
const userStore = useUserStore();
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    factoryId: '',   
    packagingId: '',
    name: '',
    stock: undefined,
    unit:'',
    goodsNos: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const unit = ref();
  //表单验证
  const validatorRules = reactive({
    stock: [{ required: true, message: '请输入库存!'},],
    name: [{ required: true, message: '请输入包材名称!'},],
    unit:[{required: true, message: '请选择单位!'}]
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  const  dictOptions = ref ([]);
  // 加载字典数据
  const fetchDictOptions = () => {
    defHttp
      .get({
        url: `/packaging/factoryProduct/dict`,
      })
      .then((res) => {
        // loading.value = false; // 加载结束
        if (res && res.length > 0) {
          console.log(res)
          dictOptions.value = res.map((item) => ({
            text: item.goodsName,
            value: item.goodsNo,
          }));
        } else {
          dictOptions.value = [];
        }
      })
      .catch((error) => {
        // loading.value = false; // 加载失败
        console.error('加载字典数据失败:', error);
        dictOptions.value = [];
      });
  };
  // watch(() => formData.packagingId, (newValue) => {
  //   console.log(newValue)
  //   if (newValue) {
  //     const dictData = initDictOptions('p_packaging,unit,unit,'+ encodeURIComponent(`id = '${newValue}'`))
  //     dictData.then(res=>{
  //       console.log(res[0])
  //       if (res[0]) {
  //         unit.value = res[0].value
  //       }else {
  //         unit.value = ''
  //       }
  //
  //     })
  //   }
  // });
  // watch(formData.packagingId, (newValue, oldValue) => {
  //   console.log(`数据从 ${oldValue} 变化到 ${newValue}`);
  //   // 这里可以执行你需要的逻辑
  // });
  
  /**
   * 新增
   */
  function add() {
    //
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    fetchDictOptions(); // 组件加载时触发
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }



  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
